﻿/*
*类名：VoiceMessageDeal
*归属：QinMing.Weixin.MessageHandlerVoice命名空间
*用途：处理微信用户发给公众号的语音消息，并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.05.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using QinMing.Config;
using QinMing.Weixin.ReturnContent;
using QinMing.WeixinContainer;
using QinMing.Tools;

namespace QinMing.Weixin.MessageHandlerVoice
{
	//语音消息处理
    public class VoiceMessageDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealVoice(weixinXML);  
            return content;
        }
        
        public string DealVoice(string weixinXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType = xn.SelectSingleNode("//MsgType").InnerText;
			string MediaId = xn.SelectSingleNode("//MediaId").InnerText.ToString().Trim();
			string Format = xn.SelectSingleNode("//Format").InnerText.ToString().Trim();
			string Recognition = xn.SelectSingleNode("//Recognition").InnerText.ToString().Trim();
			string MsgId = xn.SelectSingleNode("//MsgId").InnerText;
            string strresponse = "";

			//保存用户发来的语音信息
			SaveVoice(FromUserName, ToUserName, MediaId, Format, Recognition, MsgId);
			
			//保存用户发来的语音文件，并把发送记录写入数据库用于后期分析
			DownloadFileByMediaId(FromUserName, MediaId, Format); 
			
			//引用QinMing.Weixin.ReturnContent命名空间下的ReturnMsg类来生成固定格式的回应消息
			ReturnMsg rm = new ReturnMsg();
			strresponse = rm.ReturnText(FromUserName, ToUserName, "您刚发的语音翻译后的文字为：" + Recognition);
			//strresponse = rm.ReturnVoice(FromUserName, ToUserName, MediaId);
			
			//告知客服人员有新的留言，或者启动客服消息管理工单流程
			QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "客户发送语音内容：" + Recognition, "");  
			
            return strresponse; 
        }
		
		//把用户发来的语音信息保存到数据表表中
		public void SaveVoice(string FromUserName, string ToUserName, string MediaId, string Format, string Recognition, string MsgId)
		{
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
			
			cmd.CommandText = "insert into weixin_recv_msg (msg_type,msg_id,open_id,gh_id,recv_time,media_id,voice_format,voice_recognition) values("
			    + "'voice','" + MsgId + "','" + FromUserName + "','" + ToUserName + "',getdate(),'" + MediaId + "','" + Format + "','" + Recognition + "')";
            cmd.ExecuteScalar();
			
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
		}
		
		//使用MediaId加基础access_token从微信服务器下载语音文件
		public void DownloadFileByMediaId(string FromUserName, string MediaId, string Format)
		{
			//获取普通基础access_token
			QinMingWeixinContainer wc = new QinMingWeixinContainer();
			string access_token = wc.GetAccessToken();
			
			string imgurl = "";
			string TmpDir = "E:\\web目录\\Voice\\Upload\\";
			string TmpFileName = FromUserName + DateTime.Now.Ticks.ToString() + "." + Format;
			
			string strUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + MediaId; 
			System.Net.WebClient webClient = new System.Net.WebClient();
			webClient.DownloadFile(strUrl, TmpDir + TmpFileName);
			QinMingTools.WriteLog("用mediaid从微信服务器获取语音", strUrl);
			
			//此处可以添加用户发送语音保存到数据库记录处理，用于对粉丝进行行为分析，以及使用客户发送的语音文件
		}
    }
}